package com.ruoyi.quartz.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.quartz.service.IOrderService;
import com.ruoyi.system.domain.vo.BgdVo;
import com.ruoyi.system.domain.vo.SocVo;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.utilities.PdfTable;
import com.spire.pdf.utilities.PdfTableExtractor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 部门信息
 */
@Controller
@RequestMapping("/business/order")
public class OrderController extends BaseController {
    private String prefix = "business/order";

    @Autowired
    private IOrderService orderService;

    @RequiresPermissions("business:order:view")
    @GetMapping()
    public String dept() {
        return prefix + "/add";
    }


    @PostMapping(value = "/uploadFile/{type}")
    @ResponseBody
    public AjaxResult uploadFile(@PathVariable("type") String type, @RequestParam("file_data") MultipartFile file) throws IOException {
        if (type.equals("") || type.trim().length() == 0) {
            return AjaxResult.error("缺少文件上传类型");
        }
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        String filePath = "";
        if ("1".equals(type)) {
            filePath = "F://jizhuangxiang//";
            File folder = new File(filePath);
            if (!folder.exists() && !folder.isDirectory()) {
                boolean result = folder.mkdirs();
                if (!result) {
                    filePath = "D://jizhuangxiang//";
                }
            }
        } else {
            filePath = "F://baoguandan//";
            File folder = new File(filePath);
            if (!folder.exists() && !folder.isDirectory()) {
                boolean result = folder.mkdirs();
                if (!result) {
                    filePath = "D://baoguandan//";
                }
            }
        }
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {

            file.transferTo(dest);
            return AjaxResult.success("成功", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.error("失败");
    }

    @PostMapping(value = "/uploadFile2/{type}")
    @ResponseBody
    public AjaxResult uploadFile2(@PathVariable("type") String type, @RequestParam("file_data") MultipartFile file) throws IOException {
        if (type.equals("") || type.trim().length() == 0) {
            return AjaxResult.error("缺少文件上传类型");
        }
        if (file.isEmpty()) {
            return AjaxResult.error("文件为空");
        }

        //创建对象
        BgdVo bgdVo = new BgdVo();
        String path = "";
        try {
            //把文件写到指定文件夹
            String fileName = file.getOriginalFilename();
            String filePath = "";
            filePath = "D://PDF//";
            File folder = new File(filePath);
            if (!folder.exists() && !folder.isDirectory()) {
                folder.mkdirs();
            }
            path = filePath + fileName;
            File dest = new File(path);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }

            file.transferTo(dest);

            //获取报关单号
            //创建一个PdfDocument类的对象。
            PdfDocument pdf = new PdfDocument(path);
            //获取PDF的第一页
            PdfPageBase page = pdf.getPages().get(0);
            // 从页面指定位置提取文本
            String s = page.extractText(new Rectangle2D.Float(580, 100, 180, 190));
            // 切割字符串获得需要的字段
            String[] split = s.split("\\.");
            //报关单号赋值
            bgdVo.setBgdNo(split[2].trim().replaceAll(" ", ""));

            //获取数据
            // 加载PDF文档
            PdfDocument pdfObj = new PdfDocument(path);
            // 创建StringBuilder类的实例
            StringBuilder builder = new StringBuilder();
            // 抽取表格
            PdfTableExtractor extractor = new PdfTableExtractor(pdfObj);
            // 预设数组
            PdfTable[] tableLists = null;
            Map<String, String> map = new LinkedHashMap<>();
            // 遍历PDF，获取每一页的对象
            for (int p = 0; p < pdfObj.getPages().getCount(); p++) {
                tableLists = extractor.extractTable(p);
                if (tableLists != null && tableLists.length > 0) {
                    for (PdfTable table : tableLists) {
                        int row = table.getRowCount();
                        int column = table.getColumnCount();
                        for (int i = 0; i < row; i++) {
                            for (int j = 0; j < column; j++) {
                                String text = table.getText(i, j);
                                if (text.equals("")) {
                                    continue;
                                } else {
                                    if (text.contains("\n")) {
                                        String[] split2 = text.split("\n");
                                        map.put(split2[0], split2[1]);
                                    } else {
                                        map.put(text, null);
                                    }
                                }
                                builder.append(text).append("\r\n|\r\n");
                            }
                        }
                    }
                }
            }

            for (String str : map.keySet()) {
                if (str.contains("贸易国（地区）")) {
                    bgdVo.setCountry(map.get(str));
                }
                if (str.contains("经停港")) {
                    bgdVo.setPort(map.get(str));
                }
                if (str.contains("1 ")) {
                    String value = str;
                    String code = value.substring(2, 12);
                    bgdVo.setProductName(code);
                    String name = value.substring(12, value.indexOf(map.get("净重(千克)") + "千克") - 1);
                    bgdVo.setProductCode(name);
                }
            }
            bgdVo.setNum(map.get("件数"));
            bgdVo.setBoxWeight("");//箱皮重
            String shopOvoy = map.get("运输工具名称及航次号").toString();
            String[] str = shopOvoy.split("/");
            bgdVo.setShipName(str[0]);
            bgdVo.setOvoy(str[1]);
            bgdVo.setTdNo(map.get("提运单号"));
            bgdVo.setBoxNo("");//箱号
            bgdVo.setWeight(map.get("净重(千克)"));
            if (map.get("出口日期") != null) {
                String date = map.get("出口日期");
                String dataTmp = date.substring(0, 4) + "-";
                dataTmp += date.substring(date.length() - 4, date.length() - 2) + "-";
                dataTmp += date.substring(date.length() - 2, date.length());
                bgdVo.setOutDate(dataTmp);
            }
            if (map.get("进口日期") != null) {
                String date = map.get("进口日期");
                String dataTmp = date.substring(0, 4) + "-";
                dataTmp += date.substring(date.length() - 4, date.length() - 2) + "-";
                dataTmp += date.substring(date.length() - 2, date.length());
                bgdVo.setInDate(dataTmp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //删除本地生成的文件
            File fileTmp = new File(path);
            fileTmp.delete();
        }
        return AjaxResult.success("成功", bgdVo);
    }


    /**
     * 新增保存
     */
    @Log(title = "新增保存", businessType = BusinessType.INSERT)
    @RequiresPermissions("business:order:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(@Validated SocVo socVo) throws TaskException, SchedulerException, ParseException {
        try {
            socVo.setCreateBy(ShiroUtils.getLoginName());
            return orderService.saveSocVo(socVo);
        } catch (Exception e) {
            e.getMessage();
            return AjaxResult.error(e.getMessage());
        }
    }


}
